import React, {useEffect} from 'react'
import {Button, Form, Input, Modal, Select} from 'antd'
import SearchParam from 'components/searchParam'
import {useMount, useObjectState} from 'utils'
import {clearObject, initPageConfig, message, removeObject} from 'utils/utils'
import {getGraciousness} from 'api/venue'
import {operatedType, rightBoxSubmit, typeObject} from 'types'
import NoBorderButton from 'components/noBorderButton'
import TablePage from 'components/tablePage'
import {useQuery} from 'react-query'
import {deleteTicket, detailTicket, getTicket, insertTicket, updateTicket} from 'api/ticket'
import RightBox from 'components/rightBox'
import UploadImg from 'components/uploadImg'


export default function Ticket() {
    const [pageConfig, setPageConfig] = useObjectState(initPageConfig)
    const [pageValue, setPageValue] = useObjectState({
        selectVenueList: [],
        total: 0,
        open: false,
        initRightValue: {},
        onRightLoading: false
    })
    const [form] = Form.useForm();
    const {data, isLoading} = useQuery(['ticketList', pageConfig], async () => {
        const {data: res} = await getTicket({...removeObject(pageConfig, ['title', 'venueId'])})
        setPageValue({total: Number(res.total)})
        return res.records
    }, {})
    const onSubmit = (value: object) => {
        setPageConfig({...value, page: 1})
    }
    const onReset = () => {
        setPageConfig(() => ({...clearObject(pageConfig), ...initPageConfig}))
    }
    const operated: operatedType = ({type, data}) => {
        if (type === 'edit') {
            detailTicket(data.id).then(res => {
                setPageValue({initRightValue: res.data, open: true})
            })
        } else {
            Modal.confirm({
                title: '确定删除吗',
                okText: '确认',
                cancelText: '取消',
                onOk() {
                    deleteTicket(data.id).then(res => {
                        setPageConfig(pageConfig)
                        message({
                            message: res?.data,
                            type: 'success'
                        })
                    })
                },
                onCancel() {
                    message({
                        message: '取消删除',
                        type: 'warning'
                    })
                }
            });
        }
    }
    const pagination = {
        current: pageConfig.page,
        pageSize: pageConfig.pageSize,
        total: pageValue.total,
        onChange: (v: number, t: number) => {
            setPageConfig({
                page: v,
                pageSize: t
            })
        }
    }
    const onRightSubmit: rightBoxSubmit = async (value) => {
        // console.log(value)
        const res = pageValue.initRightValue.hasOwnProperty('id') ? await updateTicket(Object.assign(pageValue.initRightValue, value,)) : await insertTicket(value)
        message({
            message: res?.data,
            type: 'success'
        })
        onClose()
        setPageConfig({...pageConfig, update: !pageConfig.update})
    }
    const onClose = () => {
        setPageValue({open: false, initRightValue: {}})
    };
    useMount(() => {
        getGraciousness({
            page: 1,
            pageSize: 1000
        }).then(res => {
            setPageValue({selectVenueList: res.data.records})
        })
    })
    useEffect(() => {
        if (form) form.resetFields();
    }, [form, pageValue.open]);

    return (
        <div className={'ticket'}>
            <SearchParam onReset={onReset} onSubmit={onSubmit}>
                <Form.Item
                    label="文化馆"
                    name="venueId"
                >
                    <Select
                        showSearch
                        placeholder="请选择文化馆"
                        style={{width: "15rem"}}
                        filterOption={(input, option) =>
                            (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                        }
                    >
                        {
                            pageValue.selectVenueList.map((item: typeObject) => {
                                return <Select.Option key={item.id} value={item.id}>{item.title}</Select.Option>
                            })
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label="套餐名称"
                    name="title"
                >
                    <Input placeholder="请输入名称关键字"/>
                </Form.Item>
            </SearchParam>
            <TablePage
                operated={operated}
                loading={isLoading}
                columns={columns}
                dataSource={data}
                pagination={pagination}
            >
                <NoBorderButton
                    onClick={() => {
                        setPageValue({open: true, initRightValue: {}})
                    }}
                    type={'primary'} icon={'xinzeng'}
                    padding={'0.5rem 2rem'}>
                    新增
                </NoBorderButton>
            </TablePage>
            <RightBox
                open={pageValue.open}
                title={pageValue.initRightValue.hasOwnProperty('id') ? '编辑门票套餐' : '新增门票套餐'}
                onClose={onClose}
                className={'rightBox7'}
                key={'ticket'}
            >
                <Form
                    form={form}
                    initialValues={pageValue.initRightValue}
                    onFinish={onRightSubmit}
                    autoComplete="off"
                >
                    <Form.Item
                        label="所属文化馆"
                        name="venueId"
                        rules={[{required: true, message: '请选择文化馆'}]}
                    >
                        <Select
                            showSearch
                            placeholder="请选择文化馆"
                            filterOption={(input, option) =>
                                (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                            }
                        >
                            {
                                pageValue.selectVenueList.map((item: typeObject) => {
                                    return <Select.Option key={item.id} value={item.id}>{item.title}</Select.Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="title"
                        label={'套餐名称'}
                        rules={[{required: true, message: '请输入门票套餐名称'}]}
                    >
                        <Input placeholder="请输入名称"/>
                    </Form.Item>
                    <Form.Item
                        name="picture"
                        label={'套餐主图'}
                        rules={[{
                            required: true,
                            message: '请选择套餐主图'
                        }]}
                        valuePropName="picture"
                        extra="上传图片"
                    >
                        <UploadImg/>
                    </Form.Item>
                    <Form.Item
                        name="price"
                        label={'套餐价格'}
                        rules={[{required: true, message: '请输入门票套餐价格(元)'}, () => ({
                            validator(rule, value) {
                                if (/\d+/.test(value)) {
                                    return Promise.resolve();
                                } else {
                                    return Promise.reject("请输入数字");
                                }
                            }
                        })]}
                    >
                        <Input placeholder="请输入门票套餐价格(元)"/>
                    </Form.Item>
                    <Form.Item
                        name="detail"
                        label={'套餐内容'}
                        rules={[{required: true, message: '请输入门票套餐内容'}]}
                    >
                        <Input.TextArea placeholder="请输入门票套餐内容"/>
                    </Form.Item>
                    <Form.Item
                        name="note"
                        label={'套餐规则'}
                        rules={[{required: true, message: '请输入购买门票套餐使用相关的规则说明'}]}
                        style={{marginBottom: '1rem'}}
                    >
                        <Input.TextArea rows={4} placeholder="请输入购买门票套餐使用相关的规则说明"/>
                    </Form.Item>

                    <Form.Item>
                        <Button loading={pageValue.onRightLoading} type={'primary'} htmlType="submit"
                                className="login-form-button">提交</Button>
                    </Form.Item>
                </Form>
            </RightBox>
        </div>
    );
};
const columns = [
    {
        title: '文化馆',
        dataIndex: 'venueName'
    },
    {
        title: '门票套餐名称',
        dataIndex: 'title'
    },
    {
        title: '套餐主图',
        dataIndex: 'picture',
        dataType: 'img'
    },
    {
        title: '套餐价格',
        dataIndex: 'price'
    },
    {
        title: '套餐内容',
        dataIndex: 'detail'
    },
    {
        title: '套餐规则',
        dataIndex: 'note'
    }
]